package com.hl.secondHand.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hl.secondHand.common.lang.Result;
import com.hl.secondHand.entity.Mailbox;
import com.hl.secondHand.service.IMailboxService;
import com.hl.secondHand.service.IUserService;
import com.hl.secondHand.shiro.AccountProFile;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hl
 * @since 2021-06-06
 */
@RestController
@RequestMapping("/mailbox")
public class MailboxController {
    @Autowired
    IMailboxService mailboxService;
    @Autowired
    IUserService userService;

    public void addMail(int uid,int type,String content){
        Mailbox mail = new Mailbox();
        mail.setUid(uid);
        mail.setType(type);
        mail.setState(1);
        mail.setContent(content);
        mailboxService.saveOrUpdate(mail);
    }

    @RequiresAuthentication
    @RequestMapping("/mailList")
    public Result mailList(){
        int uid = ((AccountProFile) SecurityUtils.getSubject().getPrincipal()).getId();
        List<Mailbox> mail = mailboxService.list(new QueryWrapper<Mailbox>().eq("uid", uid).eq("state",1).orderByDesc("created_date"));
        return Result.succes(mail);
    }

    @RequiresAuthentication
    @RequestMapping("/readMail")
    public Result readMail(int id){
        int uid = ((AccountProFile) SecurityUtils.getSubject().getPrincipal()).getId();
        if(id == 0){    //如果id为0则是全部已读
            List<Mailbox> mail = mailboxService.list(new QueryWrapper<Mailbox>().eq("uid", uid).eq("state",1));
            for(Mailbox tmail : mail){
                tmail.setState(0);
            }
            mailboxService.saveOrUpdateBatch(mail);
        }else{
            Mailbox mail = mailboxService.getOne(new QueryWrapper<Mailbox>().eq("id", id).eq("uid", uid));
            mail.setState(0);
            mailboxService.saveOrUpdate(mail);
        }
        return Result.succes(null);
    }
}
